
#import "SecondViewController.h"
#import "SecondTypeCell.h"
#import "JSONFromDetailTypeList.h"
#import "AllProductsController.h"
#import "JSONFromDetailProductsTypeList.h"
#import "FirstPageCollectionCell.h"
#import "MyLayout.h"
#import "JSONFromBrandList.h"
#import "UMMobClick/MobClick.h"

@interface SecondViewController ()<UITableViewDataSource, UITableViewDelegate,UICollectionViewDelegate, UICollectionViewDataSource>


@property (strong, nonatomic)  UITableView *tableView;

@property (strong, nonatomic) UICollectionView* collectionView;

@property (strong, nonatomic) NSArray* lists;
//cell左边按钮的标题数组；
@property (strong, nonatomic) NSArray* leftButtonTitles;
//cell右边按钮的标题数组；
@property (strong, nonatomic) NSArray* rightButtonTitles;
//品牌数组
@property (strong, nonatomic) NSArray* brands;
@property (nonatomic, unsafe_unretained) NSInteger buttonIndex;

@property (strong, nonatomic) UIView* bottomView;

@end

@implementation SecondViewController

- (UIView*)bottomView
{
    if (!_bottomView)
    {
        _bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UISCREENWEITH, 50)];
        _bottomView.backgroundColor = LIGHTGREYColor;
    }
    return _bottomView;
}

- (UITableView*)tableView
{
    if (!_tableView)
    {
        if (UISCREENHEIGHT >= 812)
        {
            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 84, UISCREENWEITH, self.view.frame.size.height - 84) style:UITableViewStylePlain];
        }
        else
        {
            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, UISCREENWEITH, self.view.frame.size.height - 64) style:UITableViewStylePlain];
        }
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.bounces = YES;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = LIGHTGREYColor;
        [_tableView registerNib:[UINib nibWithNibName:@"SecondTypeCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    }
    return _tableView;
}

- (UICollectionView*)collectionView
{
    if (!_collectionView)
    {
        MyLayout* layout = [[MyLayout alloc]init];
        //设置水平滚动
        [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
        if (UISCREENHEIGHT >= 812)
        {
            _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 84,UISCREENWEITH, self.view.frame.size.height - 84) collectionViewLayout:layout];
        }
        else
        {
            _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64,UISCREENWEITH, self.view.frame.size.height - 64) collectionViewLayout:layout];
        }
        _collectionView.userInteractionEnabled = YES;
        _collectionView.bounces = YES;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        [_collectionView setBackgroundColor:LIGHTGREYColor];
        [_collectionView registerClass:[FirstPageCollectionCell class] forCellWithReuseIdentifier:@"cell"];
    }
    return _collectionView;
}

- (NSDictionary*)getSections
{
    return @{@"1":@"icon_prod1",@"2":@"icon_prod6",@"3":@"icon_prod3",@"4":@"icon_prod4",@"5":@"icon_prod3",@"6":@"icon_prod2"};
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.buttonIndex = 0;
    
    [self.tabBarController.tabBar setTintColor:KMainColor];
    
    [self.view addSubview:self.collectionView];
    //获取品牌产品分类
    [self getBrandList];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"SecondViewController"];//("PageOne"为页面名称，可自定义)
    self.navigationController.navigationBar.hidden = YES;
    ShowTabbar;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [self setNeedsStatusBarAppearanceUpdate];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    HiddenTabbar;
    [SVProgressHUD dismiss];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [MobClick endLogPageView:@"SecondViewController"];
}
- (IBAction)changeIndex:(UISegmentedControl *)sender
{
    if (sender.selectedSegmentIndex == 0)
    {
        [self.tableView removeFromSuperview];
        self.buttonIndex = 0;
        [self.view addSubview:self.collectionView];
        [self getBrandList];
    }
    else
    {
        [self.collectionView removeFromSuperview];
        self.buttonIndex = 1;
        self.tableView.tableFooterView = self.bottomView;
        [self.view addSubview:self.tableView];
        [self getDetailTypeList];
    }
}


#pragma mark  //弹出搜索页面
- (void)search
{
    [self showNoPush];
}

//弹出提示功能正在开发
- (void)showNoPush
{
    
    CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
    TextStatusView *customView  = [TextStatusView view];
    customView.frame = CGRectMake(10, 10, UISCREENWEITH - 80, ALERTVIEW_HEIGHT_B);
    customView.bottomLabel.text = @"该功能正在开发中，敬请期待！";
    //    customView.layer.cornerRadius = 7.0;
    //    customView.layer.masksToBounds = YES;
    [alertView setContainerView:customView];
    [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"确定", nil]];
    [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
        switch (buttonIndex)
        {
            case 0:
                return ;
                break;
            default:
                return;
                break;
        }
    }];
    [alertView show];
}


#pragma mark  //获取全部品牌分类
- (void)getBrandList
{
    //设置缓存的key
    NSString* cacheStr = [NSString stringWithFormat:@"getBrandList"];
    NSDictionary* json = @{@"platformType":@"1",
                           @"orderType":@"01",
                           @"requestService":@"getBrandList",
                           @"requestObject":@{
                                   }
                           };
    NSLog(@"json = %@",json);
    //字符串转字符串
    NSString* str = [JSONToString dictionaryToJson:json];
    //转md5
    MyAdditions* md5 = [[MyAdditions alloc]init];
    md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
    NSString* md5_Str = [md5 md5];
    NSString* url = [NSString stringWithFormat:@"%@&sign=%@",SERVER_URL,md5_Str];
    [self getBrandListWithURL:url withParam:json withCacheStr:cacheStr];
}


//读取网络或本地的全部品牌分类列表数据
- (void)readBrandListWithData:(NSData*)data
{
    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSLog(@"获取全部品牌分类json = %@",json);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if ([json isKindOfClass:[NSDictionary class]] && json)
        {
            if ([json[@"resultCode"] isEqualToString:@"0"])
            {
                NSMutableArray* arr = [NSMutableArray array];
                for (NSDictionary* dict in json[@"responseObject"][@"brandTypeList"])
                {
                    JSONFromBrandList* list = [JSONFromBrandList brandWithJSON:dict];
                    [arr addObject:list];
                }
                self.brands = [arr copy];
            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                });
            }
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                
            });
        }
        dispatch_async(dispatch_get_main_queue(), ^{
//            if (self.brands.count == 0)
//            {
//                [self createWorkView];
//            }
//            else
//            {
//                [self removeWorkView];
//            }
            [self.collectionView reloadData];
        });
    });
}

- (void)getBrandListWithURL:(NSString*)url withParam:(NSDictionary*)param withCacheStr:(NSString*)cacheStr
{
    NSLog(@"cacheStr = %@",cacheStr);
    HKTShowNetworkView* networking = [HKTShowNetworkView shareInstanceWithTitle:@"检测到您的设备没有连接网络!" withImageStr:@"no_record" withType:0 withFrame:self.tableView.frame withVC:self];
    [networking showNetworkViewWithSuccess:^{
        
        self.tableView.scrollEnabled = YES;
        [XHNetworking POST:url parameters:param cacheStr:cacheStr jsonCache:^(id jsonCache) {
            //        id result = [NSJSONSerialization JSONObjectWithData:jsonCache options:0 error:nil];
            //        NSLog(@"首页产品本地缓存信息jsonCache = %@",result);
            //无网络得到缓存 从缓存读取缓存信息;
            [self readBrandListWithData:jsonCache];
        } success:^(NSData *responseObject) {
            //网络读取数据
            [self readBrandListWithData:responseObject];
        } failure:^(NSError *error) {
            //        [self endRefresh];
            NSLog(@"error.code = %@",error.userInfo);
        }];
    } failure:^{
        self.tableView.scrollEnabled = NO;
    } click:^(NSInteger type) {
        NSLog(@"点击了什么类型的按钮%ld!",(long)type);
        if (type == 0)
        {
            //弹出网络提示
            
        }
    }];
    
}

#pragma mark  //获取细分类产品分类
- (void)getDetailTypeList
{
    //设置缓存的key
    NSString* cacheStr = [NSString stringWithFormat:@"getDetailTypeList"];
    NSDictionary* json = @{@"platformType":@"1",
                           @"orderType":@"01",
                           @"requestService":@"getDetailTypeList",
                           @"requestObject":@{
                                   }
                           };
    NSLog(@"json = %@",json);
    //字符串转字符串
    NSString* str = [JSONToString dictionaryToJson:json];
    //转md5
    MyAdditions* md5 = [[MyAdditions alloc]init];
    md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
    NSString* md5_Str = [md5 md5];
    NSString* url = [NSString stringWithFormat:@"%@&sign=%@",SERVER_URL,md5_Str];
    [self getDetailTypeListWithURL:url withParam:json withCacheStr:cacheStr];
}

//读取网络或本地的首页分组列表数据
- (void)readDetailTypeListWithData:(NSData*)data
{
    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSLog(@"获取细分类产品分类json = %@",json);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if ([json isKindOfClass:[NSDictionary class]] && json)
        {
            if ([json[@"resultCode"] isEqualToString:@"0"])
            {
                NSMutableArray* arr = [NSMutableArray array];
                for (NSDictionary* dict in json[@"responseObject"][@"detailTypeList"])
                {
                    JSONFromDetailTypeList* list = [JSONFromDetailTypeList detailTypeListWithJSON:dict];
                    [arr addObject:list];
                }
                self.lists = [arr copy];
                NSLog(@"self.allSections = %@",self.lists);
            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                });
            }
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                
            });
        }
        dispatch_async(dispatch_get_main_queue(), ^{
//            if (self.lists.count == 0)
//            {
//                [self createWorkView];
//            }
//            else
//            {
//                [self removeWorkView];
//            }
            [self.tableView reloadData];
        });
    });
}

- (void)getDetailTypeListWithURL:(NSString*)url withParam:(NSDictionary*)param withCacheStr:(NSString*)cacheStr
{
    NSLog(@"cacheStr = %@",cacheStr);
    HKTShowNetworkView* networking = [HKTShowNetworkView shareInstanceWithTitle:@"检测到您的设备没有连接网络!" withImageStr:@"no_record" withType:0 withFrame:self.tableView.frame withVC:self];
    [networking showNetworkViewWithSuccess:^{
        
        self.tableView.scrollEnabled = YES;
        
        [XHNetworking POST:url parameters:param cacheStr:cacheStr jsonCache:^(id jsonCache) {
            //无网络得到缓存 从缓存读取缓存信息;
            [self readDetailTypeListWithData:jsonCache];
        } success:^(NSData *responseObject) {
            //网络读取数据
            [self readDetailTypeListWithData:responseObject];
        } failure:^(NSError *error) {
            //        [self endRefresh];
            NSLog(@"error.code = %@",error.userInfo);
        }];
    } failure:^{
        self.tableView.scrollEnabled = NO;
    } click:^(NSInteger type) {
        if (type == 0)
        {
            //弹出网络提示
            
        }
    }];
}



//处理得到右边的数组，显示按钮标题
- (NSArray*)getRightButtonTitlesWithArray:(NSArray*)arr
{
    NSMutableArray* array = [NSMutableArray array];
    for (int i = 1; i <= [arr count]; i++)
    {
        JSONFromDetailProductsTypeList* list = [JSONFromDetailProductsTypeList detailTypeListWithJSON:arr[i-1]];
        int a = i%2;
        if (a == 0)
        {
            [array addObject:list];
        }
    }
    if (arr.count%2 == 1)
    {
        JSONFromDetailProductsTypeList* list = [[JSONFromDetailProductsTypeList alloc]init];
        list.product_detailtype_name = @"";
        [array addObject:list];
    }
//    NSLog(@"右边[array copy] = %@",[array copy]);
    return [array copy];
}

//处理得到左边的数组，显示按钮标题
- (NSArray*)getLeftButtonTitlesWithArray:(NSArray*)arr
{
    NSMutableArray* array = [NSMutableArray array];
    for (int i = 1; i <= arr.count; i++)
    {
        JSONFromDetailProductsTypeList* list = [JSONFromDetailProductsTypeList detailTypeListWithJSON:arr[i-1]];
        int a = i%2;
        if (a == 1)
        {
            [array addObject:list];
        }
    }
//    NSLog(@"左边[array copy] = %@",[array copy]);
    return [array copy];
}

//左边按钮方法
- (void)leftPostVC:(UIButton*)sender
{
    NSLog(@"左边按钮方法");
    SecondTypeCell* cell = (SecondTypeCell*)[[sender superview]superview];
    NSIndexPath* indexPath = [self.tableView indexPathForCell:cell];
    JSONFromDetailTypeList* mylist = self.lists[indexPath.section];
    NSArray* arr2 = [self getLeftButtonTitlesWithArray:mylist.detailTypeObjectList];
    JSONFromDetailProductsTypeList* list = arr2[indexPath.row];
    NSLog(@"%ld行左边按钮id=%@",(long)indexPath.row,list.product_detailtype_id);
    AllProductsController* allProductsVC = [[AllProductsController alloc]initWithNibName:@"AllProductsController" bundle:nil];
    allProductsVC.title = list.product_detailtype_name;
    allProductsVC.product_detailtype_id = list.product_detailtype_id;
    allProductsVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:allProductsVC animated:YES];
}
//右边按钮方法
- (void)rightPostVC:(UIButton*)sender
{
    NSLog(@"右边按钮方法");
    SecondTypeCell* cell = (SecondTypeCell*)[[sender superview]superview];
    NSIndexPath* indexPath = [self.tableView indexPathForCell:cell];
    JSONFromDetailTypeList* mylist = self.lists[indexPath.section];
    NSArray* arr2 = [self getRightButtonTitlesWithArray:mylist.detailTypeObjectList];
    JSONFromDetailProductsTypeList* list = arr2[indexPath.row];
    NSLog(@"%ld行右边按钮id=%@",(long)indexPath.row,list.product_detailtype_id);
    AllProductsController* allProductsVC = [[AllProductsController alloc]initWithNibName:@"AllProductsController" bundle:nil];
    allProductsVC.product_detailtype_id = list.product_detailtype_id;
    allProductsVC.title = list.product_detailtype_name;
    allProductsVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:allProductsVC animated:YES];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.lists.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    JSONFromDetailTypeList* list = self.lists[section];
    if (list.detailTypeObjectList.count%2 == 0)
    {
        return [list.detailTypeObjectList count]/2;
    }
    else
    return ([list.detailTypeObjectList count]/2) + 1;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SecondTypeCell* cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    JSONFromDetailTypeList* list = self.lists[indexPath.section];
    NSArray* arr1 = [self getLeftButtonTitlesWithArray:list.detailTypeObjectList];
    NSArray* arr2 = [self getRightButtonTitlesWithArray:list.detailTypeObjectList];
    if (arr1.count > 0)
    {
        JSONFromDetailProductsTypeList* leftList = arr1[indexPath.row];
        [cell.leftButton setTitle:leftList.product_detailtype_name forState:UIControlStateNormal];
    }
    if (arr2.count > 0)
    {
        JSONFromDetailProductsTypeList* rightList = arr2[indexPath.row];
        if (rightList)
        {
            [cell.rightButton setTitle:rightList.product_detailtype_name forState:UIControlStateNormal];
        }
    }
    if ([cell.rightButton.currentTitle isEqualToString:@""])
    {
        [cell.rightButton setHidden:YES];
    }
    else
    {
        [cell.rightButton setHidden:NO];
    }
    [cell.leftButton addTarget:self action:@selector(leftPostVC:) forControlEvents:UIControlEventTouchUpInside];
    [cell.rightButton addTarget:self action:@selector(rightPostVC:) forControlEvents:UIControlEventTouchUpInside];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60.0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 46.0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    JSONFromDetailTypeList* list = self.lists[section];
    UIView* view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UISCREENWEITH, 46)];
    view.backgroundColor = LIGHTGREYColor;
    UIView* backView = [[UIView alloc]initWithFrame:CGRectMake(0, 10, UISCREENWEITH, 36)];
    backView.backgroundColor = FFFFFFColor;
    UIImageView* imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 8.5, 19, 19)];
    NSLog(@"[self.lists[section] key] = %@",list.product_type_name);
    [imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMAGE_URL,list.product_type_logo]]
                        placeholderImage:nil];
    if ([list.product_type_logo rangeOfString:HTTP].location != NSNotFound)
    {
        [imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",list.product_type_logo]]
                     placeholderImage:nil];
    }
    [backView addSubview:imageView];
    UILabel* label = [[UILabel alloc]initWithFrame:CGRectMake(35, 8.5, 150, 19)];
    label.font = SetFont(14);
    label.textAlignment = NSTextAlignmentLeft;
    label.textColor = E7E7EColor;
    label.text = list.product_type_name;
    [backView addSubview:label];
    UIView* lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 35, UISCREENWEITH, 1)];
    lineView.backgroundColor = LIGHTGREYColor;
    [backView addSubview:lineView];
    [view addSubview:backView];
    return view;
}

#pragma  mark - 集合视图的代理方法

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.brands.count;
}
- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    JSONFromBrandList* brand = self.brands[indexPath.row];
    FirstPageCollectionCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.myImageView.backgroundColor = LIGHTGREYColor;
    [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMAGE_URL,brand.brand_logo]]
                             placeholderImage:LoadImage(@"")];
    if ([brand.brand_logo rangeOfString:HTTP].location != NSNotFound)
    {
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",brand.brand_logo]]
                            placeholderImage:LoadImage(@"")];
    }
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"...推出产品库");
    //跳转到所有产品库
    JSONFromBrandList* list = self.brands[indexPath.row];
    AllProductsController* allProductsVC = [[AllProductsController alloc]initWithNibName:@"AllProductsController" bundle:nil];
    allProductsVC.title = list.brand_name;
    allProductsVC.brand_id = list.brand_id;
    allProductsVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:allProductsVC animated:YES];
}


@end
